<template>
  <view class="container">
    <image :src="$Config.get('imageUrl')+'/user/login_bg.png'" class="bg"/>
    <view class="content">
      <image :src="$Config.get('imageUrl')+'/user/login_logo.png'" class="logo"/>
      <view class="title">宝洞经济 共享一切</view>
      <view class="login-btn">
        <!-- 获取微信用户信息 -->
        <button class="button " @click.stop="getUserProfile">
          <text class="iconfont icon-weixin" ></text>
          <span>微信用户一键登录</span>
        </button>
      </view>
    </view>

<!--    <view class="no-login-btn">-->
<!--      <button class="button btn-normal" @click="handleCancel">暂不登录</button>-->
<!--    </view>-->


<!--    <u-popup :show="popup" closeable round="24rpx" mode="center" @close="close">-->
<!--      <view class="popup">-->
<!--        <view class="title">-->
<!--          设置头像昵称-->
<!--        </view>-->
<!--        <view class="p-content">-->
<!--          <view class="item">-->
<!--            <view class="avatar">-->
<!--              <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" >-->
<!--                <image :src="avatarUrl" mode="" />-->
<!--              </button>-->
<!--            </view>-->
<!--          </view>-->
<!--          <view class="item">-->
<!--            <view class="label">昵称</view>-->
<!--            <view class="value un-input">-->
<!--              <input type="nickname" @blur="blurname" v-model="username" placeholder="请输入昵称"/>-->
<!--            </view>-->
<!--          </view>-->
<!--          <view class="item">-->
<!--            <view class="label">地区</view>-->
<!--            <view class="value">-->
<!--              <select-region ref="sRegion" v-model="region" :column="2" :defaultval="defaultRegion" placeholder="请选择省市"/>-->
<!--            </view>-->
<!--          </view>-->
<!--        </view>-->
<!--        <view class="btn">-->
<!--          <button class="button btn-primary" @click="setAvatarName">确定</button>-->
<!--        </view>-->
<!--      </view>-->
<!--    </u-popup>-->
  </view>
</template>

<script>
  import store from '@/store'
  import storage from '@/utils/storage'
  import { isEmpty } from '@/utils/util'
  // import SelectRegion from '@/page_work/address/select-region/select-region'
  export default {
    // components: {
    //   SelectRegion
    // },
    data() {
      return {
        // 商城基本信息
        storeInfo: undefined,
        // 微信小程序登录凭证 (code)
        // 提交到后端，用于换取openid
        code: '',
        popup: false,
        userInfo:{},
        avatarUrl: '',
        username: '',
        provinceId: '',
        cityId: '',
        region: [],
        defaultRegion: [],
      }
    },
    created() {
      // 获取商城基本信息
      // this.getStoreInfo()
    },
    onShow(){

    },
    methods: {
      // 获取code
      // https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
      getCode() {
        return new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: res => {
              resolve(res.code)
            },
            fail: reject
          })
        })
      },

      // 获取微信用户信息(新版)
      getUserProfile() {
        const app = this
        wx.canIUse('getUserProfile') && wx.getUserProfile({
          lang: 'zh_CN',
          desc: '获取用户相关信息',
          success({ userInfo }) {
            // console.log('用户同意了授权')
            // console.log('userInfo：', userInfo)
            app.avatarUrl = userInfo.avatarUrl;
            // 授权成功事件
            app.onAuthSuccess(userInfo)
          },
          fail() {
            console.log('用户拒绝了授权')
          }
        })
      },

      // 授权成功事件
      // 这里分为两个逻辑:
      // 1.将code和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
      // 2.如果不存在该用户, 则显示注册页面, 需填写手机号
      // 3.如果后端报错了, 则显示错误信息
      async onAuthSuccess(userInfo) {
        const app = this
        // 提交到后端
        let params ={
          code: await app.getCode(),
          userInfo
        }
        let shareId = storage.get('shareUserId');
        if(shareId){
          params['shareUserId']=shareId
        }
        store.dispatch('LoginMpWx', params)
        .then(result => {
          // result.data.userInfo.firstLogin  = true;
          // console.log('result.data>>>>',result.data)
          if(result.data.userInfo.firstLogin || (result.data.userInfo.provinceId === 0 && result.data.userInfo.cityId === 0)){
            // app.popup = true;
            this.$navTo('page_work/user/setUserInfo',{from:'login'})
            return;
          }
          app.loginSuccess();
        })
          .catch(err => {
            const resultData = err.result.data
            // 显示错误信息
            if (isEmpty(resultData)) {
              app.$toast(err.result.message)
            }
            // 跳转回原页面
            if (resultData.isBack) {
              setTimeout(() => app.onNavigateBack(1), 2000)
            }
            // 判断还需绑定手机号
            if (resultData.isBindMobile) {
              app.onEmitSuccess(userInfo)
            }
          })
      },

      // 将oauth提交给父级
      // 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
      async onEmitSuccess(userInfo) {
        const app = this
        app.$emit('success', {
          oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
          code: await app.getCode(), // 微信登录的code, 用于换取openid
          userInfo // 微信用户信息
        })
      },

      /**
       * 暂不登录
       */
      handleCancel() {
        // 跳转回原页面
        this.onNavigateBack()
      },

      loginSuccess(){
        const app = this;
        // 一键登录成功
        app.$toast('登录成功')
        // 相应全局事件订阅: 刷新上级页面数据
        uni.$emit('syncRefresh', true)
        // 跳转回原页面
        setTimeout(() => app.onNavigateBack(), 2000)
      },
      /**
       * 登录成功-跳转回原页面
       */
      onNavigateBack(delta = 1) {
        const pages = getCurrentPages()
        if (pages.length > 1) {
          uni.navigateBack({
            delta: Number(delta || 1)
          })
        } else {
          this.$navTo('pages/index/index')
        }
      },

      onChooseAvatar(e) {
        this.avatarUrl = e.detail.avatarUrl
        // this.$request.urlFileUpload('wx/storage/upload',{
        //   files: [{path:e.detail.avatarUrl}], // 必填 临时文件路径 格式: [{path: "图片地址"}]
        //   // data:"向服务器传递的参数", //可不填
        //   // name:"后台接受文件key名称", //默认 file
        // }).then(res=>{
        //   console.log(res)
        //   this.avatarUrl = res[0].data.url;
        // }).catch(err=>{
        //   this.$toast(err.errmsg)
        // })
      },
      blurname(e){
        this.username = e.detail.value
      },
      setAvatarName(){
        const app = this;
        if(app.avatarUrl == ''){
          app.$toast('请选择头像')
          return;
        }
        if(app.username == ''){
          app.$toast('请输入昵称')
          return;
        }
        if(app.region.length < 2){
          app.$toast('请选择省市')
          return;
        }
        const params = {
          nickName:app.username,
          avatarUrl:app.avatarUrl,
          provinceId:app.region[0].id,
          cityId:app.region[1].id,
        }
        app.$request.post('wx/auth/setNickName',params).then(res=>{
          store.commit('UPDATE_USER_NAME_AVATAR', { userName:app.username, avatar:app.avatarUrl })
          app.loginSuccess();
        }).catch(err=>{
          app.$toast(err.errmsg)
        })
      },
      close() {
        this.popup = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    font-size: 32rpx;
    min-height: 100vh;
    background: linear-gradient(0deg, #fff 0%, #7D91FF 75%, #6BB9FF 100%);
    position: relative;
  }
  .bg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    image{
      width: 100%;
      height: 100%;
    }
  }
  .content{
    top: 0;
    left: 0;
    width: 100%;
    min-height: 100vh;
    z-index: 1;
    display: flex;
    flex-direction: column;
    gap: 40rpx;
    align-items: center;
    padding: 200rpx 0;
    position: relative;
    box-sizing: border-box;
  }
  .logo{
    width: 200rpx;
    height: 200rpx;
  }
  .title{
    font-size: 40rpx;
    font-weight: 400;
    color: #FFFFFF;
  }
  .login-btn{
    position: absolute;
    bottom: 400rpx;
    padding: 0 60rpx;
    width: 100%;
    box-sizing: border-box;
    .button{
      height: 88rpx;
      background: #1777FF;
      border-radius: 60rpx;
      display: flex;
      gap:12rpx;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      font-weight: 500;
      color: #FFFFFF;
      letter-spacing: 1px;
      image{
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  .popup{
    width: 600rpx;
    padding:20rpx;
    box-sizing: border-box;
    .title{
      font-size: 32rpx;
      font-weight: 500;
      color: #010812;
      text-align: center;
    }
    button{
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
      background: #f1f0f0;
      &:after{
        display: none;
      }
    }
    .p-content{
      margin-top: 40rpx;
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      .item{
        display: flex;
        gap: 20rpx;
        align-items: center;
        .label{
          font-size: 28rpx;
          font-weight: 500;
          color: #010812;
        }
        .avatar{
          width: 160rpx;
          height: 160rpx;
          border-radius: 50%;
          overflow: hidden;
          margin: 0 auto;
          image{
            width: 100%;
            height: 100%;
          }
        }
        .value{
          height: 92rpx;
          overflow: hidden;
          background: #f1f0f0;
          border-radius: 10rpx;
          box-sizing: border-box;
          flex:1;
        }
        .un-input{
          padding: 26rpx 32rpx;
        }
      }
    }
    .btn{
      margin-top: 40rpx;
      display: flex;
      justify-content: center;
      button{
        width: 200rpx;
        height: 60rpx;
        background: #1777FF;
        border-radius: 30rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #FFFFFF;
      }
    }
  }
</style>
